package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    /**
     * 过滤器处理
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req =(HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

//        A. 获取本次请求的URI
        String requestURI = req.getRequestURI();
        log.info("拦截到请求"+requestURI);
          //定义不需要处理的请求路径
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
//        B. 判断本次请求, 是否需要处理
        boolean check = check(urls, requestURI);
        if(check){
            log.info("本次申请不需要过滤",requestURI);
            chain.doFilter(req,resp);
            return;
        }
//        C. 如果不需要，则直接放行
//        D. 判断登录状态，如果已登录，则直接放行
        if(req.getSession().getAttribute("employee") != null){
            log.info("用户已登录，用户id为：{}",req.getSession().getAttribute("employee"));
           chain.doFilter(req,resp);
            return;
        }
        if(req.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",req.getSession().getAttribute("user"));
            chain.doFilter(req,resp);
            return;
        }
//        E. 如果未登录, 则返回未登录结果
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String[] urls ,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
